package leetcode.recursive;


import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

//46. 全排列
public class Permute {
    public static void main(String[] args) {
        System.out.println(permute(new int[]{1, 2, 3}).toString());
    }

    static List<List<Integer>> res = new ArrayList<>();
    static List<Integer> path = new ArrayList<>();

    public static List<List<Integer>> permute(int[] nums) {
        for (int x : nums) {
            path.add(x);
        }
        int n = path.size();
        backtrack(n, 0);
        return res;

    }

    private static void backtrack(int n, int start) {
        if (start == n) {
            res.add(new ArrayList<>(path));
            return;
        }
        for (int i = start; i < n; i++) {
            Collections.swap(path, start, i);
            backtrack(n, start + 1);
            //撤销
            Collections.swap(path, start, i);
        }
    }


    public static List<List<Integer>> permute2(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> path = new ArrayList<>();
        boolean[] used = new boolean[nums.length];
        dfs(res, path, nums.length, 0, used, nums);
        return res;
    }

    private static void dfs(List<List<Integer>> res,
                            List<Integer> path,
                            int length, int start, boolean[] used, int[] nums) {
        if (start == length) {
            res.add(new ArrayList<>(path));
            return;
        }
        for (int i = 0; i < length; i++) {
            if (!used[i]) {
                path.add(nums[i]);
                used[i] = true;
                dfs(res, path, length, start + 1, used, nums);
                //撤销,与递归前正好相反且对称
                used[i] = false;
                path.remove(path.size() - 1);
            }
        }
    }

    // 二战
    public List<List<Integer>> permuteP(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> path = new ArrayList<>();
        boolean[] used = new boolean[nums.length];
        backtrace(res, path, used, nums, 0, nums.length);
        return res;
    }

    private void backtrace(List<List<Integer>> res, List<Integer> path,
                           boolean[] used, int[] nums,
                           int start, int length) {
        if (start == length) {
            res.add(new ArrayList<>(path));
            return;
        }
        for (int i = 0; i < length; i++) {
            if (!used[i]) {
                used[i] = true;
                path.add(nums[i]);
                backtrace(res, path, used, nums, start + 1, length);
                // 回溯
                path.remove(path.size() - 1);
                used[i] = false;
            }
        }
    }
}
